package activity.addressmanage;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.hutoubenjg.R;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

import activity.login.ActivityLogin;
import adapter.AddressListAdapter;
import base.BaseActivity;
import bean.MyAddressBean;
import presenter.UserPresenter;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.SPUtils;
import util.volley.ResultEntity;

/**
 * 我的收货地址
 */
public class AddressListActivity extends BaseActivity implements Observer {
    ImageView back;
    ListView order_listView;
    TextView tvTitle;
    RelativeLayout address_add;//添加收货地址
    TextView remain_addresscount;//还有几个地址可以添加
    TextView address_img;
    private List<MyAddressBean> list;
    UserPresenter userPresenter;
    String uid;
    int tid;//删除的是哪一条
    private Dialog dialog;// 自定义Dialog
    AddressListAdapter adapter;
    String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_list);
        tvTitle.setText(getString(R.string.receiver_address));
        type = getIntent().getStringExtra("type");
        uid = (String) SPUtils.get(this, null, Const.ID, "");
        userPresenter = new UserPresenter(this);
        userPresenter.queryAddress(IsUtilUid.sId(), uid);
        showProgressDialog("获取中,请稍后", true);
        init();
        showExtraDialog();

        //退出登录的广播
        IntentFilter intentFilterExit = new IntentFilter(
                "addaddress");
        registerReceiver(nichengBroadcastReceiver, intentFilterExit);

    }

    BroadcastReceiver nichengBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            userPresenter.queryAddress(IsUtilUid.sId(), uid);
        }

        ;
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(nichengBroadcastReceiver);
    }

    /**
     * listView操作
     */
    private void init() {
        order_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (type.equals("1")) {
                    Intent intent = new Intent();
                    intent.putExtra("name", list.get(position).getContactname());
                    intent.putExtra("addaress", list.get(position).getProvince() + list.get(position).getCity() + list.get(position).getArea() + list.get(position).getDetailinfo());
                    intent.putExtra("phone", list.get(position).getMobile());
                    intent.putExtra("id", list.get(position).getId() + "");
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    Intent intent = new Intent(AddressListActivity.this, AddressDetailActivity.class);
                    intent.putExtra("id", list.get(position).getId() + "");
                    intent.putExtra("type", "edit");
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("bean", list.get(position));
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        });
        //长按
        order_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                tid = list.get(position).getId();
                dialog.show();
                return true;
            }
        });
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.address_add:
                if ((remain_addresscount.getText().toString()).equals("还可以添加0个收货地址")) {
                    ByAlert.alert("收货地址最多10条");
                } else {
                    Intent intent = new Intent(AddressListActivity.this, AddressDetailActivity.class);
                    intent.putExtra("type", "add");
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getCode().equals("1111")) {
                ByAlert.alert("登录异常，请重新登录");
                Intent intent = new Intent(AddressListActivity.this, ActivityLogin.class);
                startActivity(intent);
                try {
                    dialog.dismiss();
                    closeProgressDialog();
                } catch (Exception e) {
                }
                finish();
            } else if (entity.getEventType() == UserPresenter.query_address_success) {
                list = (List<MyAddressBean>) entity.getData();
                if (list != null) {
                    if (list.size() > 0) {
                        adapter = new AddressListAdapter(this, list);
                        order_listView.setAdapter(adapter);
                        remain_addresscount.setText("还可以添加" + (10 - list.size()) + "个收货地址");
                        order_listView.setVisibility(View.VISIBLE);
                        address_img.setVisibility(View.GONE);
                    } else {
                        order_listView.setVisibility(View.GONE);
                        address_img.setVisibility(View.VISIBLE);
                    }
                } else {
                    order_listView.setVisibility(View.GONE);
                    address_img.setVisibility(View.VISIBLE);
                }

            } else if (entity.getEventType() == UserPresenter.query_address_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.delete_address_success) {
                ByAlert.alert(entity.getData());
                userPresenter.queryAddress(IsUtilUid.sId(), uid);
                adapter.notifyDataSetChanged();

//                Iterator<MyAddressBean> iterator = list.iterator();
//                while (iterator.hasNext()) {
//                    MyAddressBean bean = iterator.next();
//                    if (tid == bean.getId()) {
//                        iterator.remove();
//                        adapter.notifyDataSetChanged();
//                        remain_addresscount.setText("还可以添加"+(10-list.size())+"个收货地址");
//                        break;
//                    }
//                }
            } else if (entity.getEventType() == UserPresenter.delete_address_fail) {
                ByAlert.alert(entity.getData());
            }
        }
        try {
            dialog.dismiss();
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    /**
     * 删除Dialog
     */
    private void showExtraDialog() {
        dialog = new Dialog(this, R.style.rel_dialog);
        View view = LayoutInflater.from(this).inflate(
                R.layout.dialog_delete, null);
        dialog.setContentView(view);

        TextView dialog_ok = (TextView) view.findViewById(R.id.dialog_ok);
        TextView dialog_quxiao = (TextView) view.findViewById(R.id.dialog_quxiao);
        dialog.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                userPresenter.deleteAddress(IsUtilUid.sId(), uid, tid + "");
                showProgressDialog("删除中,请稍后", true);
            }
        });
        dialog_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialog.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }
}
